<?php
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\ArchivesDeceasedModel;
use app\admin\model\CustomerInfoModel;
use app\admin\model\MaintenanceProjectModel;
use app\admin\model\OrderModel;
use app\admin\model\ServiceBuriedModel;
use app\admin\model\ServiceDepositModel;
use app\admin\model\ServiceMoveModel;
use app\admin\model\ServiceWeibaoModel;
use app\admin\model\TombareaRowColModel;
use cmf\controller\AdminBaseController;
use think\Db;

class ServiceController extends AdminBaseController
{
    public function initialize()
    {
        parent::initialize();
    }

    /*服务管理-落葬管理*/
    public function index()
    {
        $model = new ServiceBuriedModel();//Db::name("serviceBuried");

        $service_status = $this->request->param("service_status");
        $start_time = $this->request->param("start_time");
        $end_time = $this->request->param("end_time");
        $select_name = $this->request->param("service_name");
        $where = [];
        $where[] = array('pay_status',"=",1);
        if (empty($start_time)){
            $start_time = 0;
        }else{
            $start_time = strtotime($start_time);
        }
        if (empty($end_time)) {
            $end_time = 99999999999;
        }else{
            $end_time = strtotime($end_time . '+1 day');
        }

        if (!empty($service_status)) {
            $where[] = array('service_status',"=",$service_status);
        }
        if(!empty($select_name)){
            $where[] = array('dealer_user|buyer_name|handle_name','like',"%".$select_name."%");
        }
        $results = $model
            ->where($where)
            ->where('buried_time','>=',$start_time)
            ->where('buried_time','<=',$end_time)
            ->order('add_time desc')
            ->paginate(10);
        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("service_status", $service_status);
        $this->assign("page", $page);

        return $this->fetch();
    }
    public function burie_edit(){
        if ($this->request->isPost()){


        }
        $id = $this->request->param('id');

        return $this->fetch();
    }

    /*服务管理-寄存管理*/
    public function depositindex()
    {

        $model = Db::name("serviceDeposit");

        $service_status = $this->request->param("service_status");
        $start_time = $this->request->param("start_time");
        $end_time = $this->request->param("end_time");
        $select_name = $this->request->param("service_name");

        $where = [];
        $where[] = array('submit_status',"gt",1);
        if (empty($start_time)){
            $start_time = 0;
        }else{
            $start_time = strtotime($start_time);
        }
        if (empty($end_time)) {
            $end_time = 99999999999;
        }else{
            $end_time = strtotime($end_time . '+1 day');
        }

        if (!empty($service_status)) {
            $where[] = array('service_status',"=",$service_status);
        }
        if(!empty($select_name)){
            $where[] = array('dealer_user|buyer_name|handle_name|dead_name','like',"%".$select_name."%");
        }

        $results = $model
                    ->where($where)
                    ->where('deposit_time','>=',$start_time)
                    ->where('deposit_time','<=',$end_time)
                    ->order('add_time desc')
                    ->paginate(10);

        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("service_status", $service_status);
        $this->assign("page", $page);

        return $this->fetch();
    }
    /*服务管理-迁墓管理*/
    public function moveindex()
    {
        $model = Db::name("serviceMove");

        $start_time = $this->request->param("start_time");
        $end_time = $this->request->param("end_time");
        $select_name = $this->request->param("service_name");
        $service_status = $this->request->param("service_status");
        $where = [];

        if (empty($start_time)){
            $start_time = 0;
        }else{
            $start_time = strtotime($start_time);
        }
        if (empty($end_time)) {
            $end_time = 99999999999;
        }else{
            $end_time = strtotime($end_time . '+1 day');
        }
        if (!empty($service_status)) {
            $where[] = array('service_status',"=",$service_status);
        }
        if(!empty($select_name)){
            $where[] = array('buyer_name|handle_name','like',"%".$select_name."%");
        }

        $results = $model
            ->where($where)
            ->where('move_time','>=',$start_time)
            ->where('move_time','<=',$end_time)
            ->where('pay_status',"1")
            ->order('add_time desc')
            ->paginate(10);

        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("service_status", $service_status);
        $this->assign("page", $page);

        return $this->fetch();
    }
    /*服务管理-维保管理*/
    public function weibaoindex()
    {
        $model = Db::name("serviceWeibao");

        $start_time = $this->request->param("start_time");
        $end_time = $this->request->param("end_time");
        $start_time1 = $this->request->param("start_time1");
        $end_time1 = $this->request->param("end_time1");
        $select_name = $this->request->param("service_name");
        $service_status = $this->request->param("service_status");

        $where = [];
        $where[] = array('pay_status',"=",1);
        if (empty($start_time)){
            $start_time = 0;
        }else{
            $start_time = strtotime($start_time);
        }
        if (empty($end_time)) {
            $end_time = 99999999999;
        }else{
            $end_time = strtotime($end_time . '+1 day');
        }
        if (empty($start_time1)){
            $start_time1 = 0;
        }else{
            $start_time1 = strtotime($start_time1);
        }
        if (empty($end_time1)) {
            $end_time1 = 99999999999;
        }else{
            $end_time1 = strtotime($end_time1 . '+1 day');
        }
        if (!empty($service_status)) {
            $where[] = array('service_status',"=",$service_status);
        }
        if(!empty($select_name)){
            $where[] = array('business_num|handle_name','like',"%".$select_name."%");
        }

        $results = $model
            ->where($where)
            ->where('register_time','>=',$start_time)
            ->where('register_time','<=',$end_time)
            ->where('deliver_time','>=',$start_time1)
            ->where('deliver_time','<=',$end_time1)
            ->order('add_time desc')
            ->paginate(10);

        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("service_status", $service_status);
        $this->assign("page", $page);

        return $this->fetch();
    }

    /*落葬任务完成--跳转传值*/
    public function buriedfinish()
    {
        if ($this->request->isPost()){
            $data = $this->request->param();
            $buried_id = $data['service_id'];
            // 添加数据
            $path_url=$data['photo_urls'];
            if (!isset($data['photo_urls'][0]) ||  empty($data['photo_urls'][0])){
                $this->error("请上传反馈图片");
            }
            // 先删除confrim表对应的数据
            Db::name("serviceConfirm")->where(array('service_id' => $data['service_id'], 'task_type' => $data['task_type']))->delete();
            // 添加的数组
            $album = array(
                'service_id'=> $data['service_id'],
                'task_type' => $data['task_type']
            );
            $name=$data['photo_names'];
            for($i = 0; $i < count($path_url) - 1; $i++){
                $album['name']=$name[$i];
                $album['url']=$path_url[$i];
                Db::name("serviceConfirm")->insert($album);
            }

            // 更新落葬管理表的确认内容字段
            $data11_info =  ServiceBuriedModel::where('id', $data['service_id'])->find();

            $order_id = $data11_info['order_id'];
            $customer_id = $data11_info['customer_id'];
            $order_info = OrderModel::getOrderByid($data11_info['order_id']);
            $funeral_time =  date_to_unixtime($data['funeral_time']);
//            $funeral_time = $data['funeral_time'];
            if (!$order_info['whq_start_date']){
                $ad_info = ArchivesDeceasedModel::where(['tomb_id' => $data11_info['tomb_id'],'customer_id'=>$customer_id])->order('funeral_time asc ')->field('date_funeral,funeral_time')->find();
                if ($ad_info) {
//                    OrderModel::update(['whq_start_date' => date_to_unixtime($ad_info['funeral_time']), 'whq_end_date' => unixtime_to_date_inc(date_to_unixtime($ad_info['funeral_time']), 20)], ['order_id' => $order_id]);
                    OrderModel::update(['whq_start_date' => $funeral_time, 'whq_end_date' => unixtime_to_date_inc($funeral_time, 20)], ['order_id' => $order_id]);
                }
            }
            $data11['buried_time'] = $funeral_time;
            $data11['funeral_time'] = $funeral_time;
            $data11['confirm_content'] = $data['confirm_content'];
            $data11['service_status'] = '3';
            ServiceBuriedModel::update($data11,['id'=> $data['service_id']]);
            ArchivesDeceasedModel::update(['buied_status'=>3],['buried_id'=>$buried_id]);
            TombareaRowColModel::get_tomb_regulation($data11_info['tomb_id'],$customer_id);
            $this->success("添加成功！", url("Service/index"));
        }
        $id = $this->request->param('id');
        $tasktype = $this->request->param('TaskType');
        $result = Db::name("serviceBuried")->field('confirm_content,service_status,tomb_num,funeral_time')->where('id', $id)->find();
        $this->assign($result);
        $this->assign('funeral_time',unixtime_to_date($result['funeral_time']));

        // 查找图片
        $photourls = Db::name("serviceConfirm")->field('url,name')
            ->where(array('service_id' => $id, 'task_type' => $tasktype))
            ->select();
        $this->assign("photourls",$photourls);

        $this->assign("TaskType", $tasktype);
        $this->assign("service_id", $id);
        $this->assign("service_status", $result['service_status']);

        return $this->fetch();
    }
    /*落葬任务完成提价表单--跳转传值*/
    public function buriedfinish_post(){

    }




    /*寄存任务完成--跳转传值*/
    public function depositfinish()
    {
        if ($this->request->isPost()){
            $data = $this->request->param();
            // 添加数据
            $path_url=$data['photo_urls'];
            $service_id=$data['service_id'];

            if (!isset($data['photo_urls'][0]) ||  empty($data['photo_urls'][0])){
                $this->error("请上传反馈图片");
            }
            // 先删除confrim表对应的数据
            Db::name("serviceConfirm")->where(array('service_id' => $service_id, 'task_type' => $data['task_type']))->delete();
            // 添加的数组
            $album = array(
                'service_id'	=> $service_id,
                'task_type'     =>$data['task_type']
            );
            $name=$data['photo_names'];
            for($i = 0; $i < count($path_url) - 1; $i++){
                $album['name']=$name[$i];
                $album['url']=$path_url[$i];
                Db::name("serviceConfirm")->insert($album);
            }
            // 更新寄存管理表的确认内容字段
            $data11_info = ServiceDepositModel::where('id',$service_id)->find();
            $data11['confirm_content'] = $data['confirm_content'];
            $data11['service_status'] = '3';
            $data11['add_time'] = time();

            $mw_id = $data11_info['tomb_id'];
            $customer_id = $data11_info['customer_id'];

            ServiceDepositModel::update($data11,['id'=>$service_id]);
            ArchivesDeceasedModel::update(['deposit_status'=>3],['deposit_status'=>$service_id]);
            if ($data['type']==0){
//                OrderModel::update(['status'=>4],['customer_id'=>$customer_id,'tomb_id'=>$mw_id]);
                TombareaRowColModel::update(['col_status'=>7],['colID'=>$mw_id]);
            }else{
                TombareaRowColModel::update(['col_status'=>1],['colID'=>$mw_id]);
            }
            $this->success("添加成功！", url("Service/depositindex"));
        }
        $id = $this->request->param('id');
        $tasktype = $this->request->param('TaskType');
        $result = Db::name("serviceDeposit")->field('confirm_content,service_status,tomb_num,type')
            ->where('id', $id)
            ->find();
        $this->assign($result);
        // 查找图片
        $photourls = Db::name("serviceConfirm")->field('url,name')
            ->where(array('service_id' => $id, 'task_type' => $tasktype))
            ->select();
        $this->assign("photourls",$photourls);

        $this->assign("TaskType", $tasktype);
        $this->assign("service_id", $id);
        $this->assign("service_status", $result['service_status']);

        return $this->fetch();
    }
    /*寄存任务完成提价表单--跳转传值*/
    public function depositfinish_post()
    {

    }


    /*迁墓任务完成--跳转传值*/
    public function movefinish()
    {
        $id = $this->request->param('id');
        $tasktype = $this->request->param('TaskType');
        $result = Db::name("serviceMove")->field('confirm_content,service_status,tomb_num,tomb_id,customer_id')
            ->where('id', $id)
            ->find();
        $this->assign($result);

        // 查找图片
        $photourls = Db::name("serviceConfirm")->field('url,name')
            ->where(array('service_id' => $id, 'task_type' => $tasktype))
            ->select();
        $this->assign("photourls",$photourls);

        $this->assign("TaskType", $tasktype);
        $this->assign("service_id", $id);
        $this->assign("service_status", $result['service_status']);

        return $this->fetch();
    }
    /*迁墓任务完成提价表单--跳转传值*/
    public function movefinish_post()
    {
        $data = $this->request->param();
        // 添加数据
        $path_url=$data['photo_urls'];

        if (!isset($data['photo_urls'][0]) ||  empty($data['photo_urls'][0])){
            $this->error("请上传反馈图片");
        }
        // 先删除confrim表对应的数据
        Db::name("serviceConfirm")->where(array('service_id' => $data['service_id'], 'task_type' => $data['task_type']))->delete();
        // 添加的数组
        $album = array(
            'service_id'	=> $data['service_id'],
            'task_type'     =>$data['task_type']
        );
        $name=$data['photo_names'];
        for($i = 0; $i < count($path_url) - 1; $i++){
            $album['name']=$name[$i];
            $album['url']=$path_url[$i];

            Db::name("serviceConfirm")->insert($album);
        }

        // 更新迁墓管理表的确认内容字段
        $data11['confirm_content'] = $data['confirm_content'];
        $data11['service_status'] = '3';
        ServiceMoveModel::update($data11,['id'=>$data['service_id']]);

        // 逝者信息表的迁出状态改为已迁出，用于页面判断用
        ArchivesDeceasedModel::update(['move_status'=>3],["servicemove_id"=>$data['service_id']]);

        // 更新墓位表的状态为部分安葬或者无产品
        $deathlist = Db::name("archives_deceased")->where(array("move_status"=>'1',"tomb_id"=> $data['tomb_id'],"customer_id"=> $data['customer_id'] ))->select();
        
        if(sizeof($deathlist) > 0){
            // 还有未迁出的逝者信息时更新表为部分安葬
            $tomb['col_status'] = 6;
            TombareaRowColModel::update($tomb,["colID"=>$data['tomb_id']]);
        }else{
            // 没有落葬的人以后改状态为無產品
            $tomb['col_status'] = 0;
            TombareaRowColModel::update($tomb,["colID"=>$data['tomb_id']]);
            CustomerInfoModel::update(['move_status'=>0],['id'=>$data['customer_id']]);
        }
        $this->success("添加成功！", url("Service/moveindex"));
    }


    /*维保任务完成--跳转传值*/
    public function weibaofinish()
    {
        $ajax = $this->request->param('ajax',0);
        $id = $this->request->param('id');
        $tasktype = $this->request->param('TaskType');
        $result = Db::name("serviceWeibao")->field('register_time,confirm_content,service_status,handle_name,tomb_num')
            ->where('id', $id)
            ->find();
        $this->assign($result);

        // 查找图片 维修前
        $photourls = Db::name("serviceConfirm")->field('url,name')
            ->where(array('service_id' => $id, 'task_type' => $tasktype,'weibao_type'=>1))
            ->select();
        $this->assign("photourls",$photourls);

        // 查找图片 维修后
        $photourls1 = Db::name("serviceConfirm")->field('url,name')
            ->where(array('service_id' => $id, 'task_type' => $tasktype,'weibao_type'=>2))
            ->select();
        $this->assign("photourls1",$photourls1);

        $this->assign("TaskType", $tasktype);
        $this->assign("service_id", $id);
        $this->assign("ajax", $ajax);
        $this->assign("service_status",$result['service_status']==1?'未确认':($result['service_status']==2?'已确认':($result['service_status']==3?"已完成":$result['service_status']==4?"已上传":'')));
        $this->assign("register_time", date('Y.m.d',$result['register_time']));
//        $this->assign("$result", $result['service_status']);

        return $this->fetch();
    }
    /*寄存任务完成提价表单--跳转传值*/
    public function weibaofinish_post()
    {
        $data = $this->request->param();
        // 添加数据
        $path_url=$data['photo_urls'];
        $path_url1=$data['photo_urls1'];

        if (!isset($data['photo_urls'][0]) ||  empty($data['photo_urls'][0])){
            $this->error("请上传维修前图片");
        }

        if (!isset($data['photo_urls1'][0]) ||  empty($data['photo_urls1'][0])){
            $this->error("请上传维修后照片");
        }
        // 先删除confrim表对应的数据
        Db::name("serviceConfirm")->where(array('service_id' => $data['service_id'], 'task_type' => $data['task_type']))->delete();
        // 维修前添加的数组
        $album = array(
            'service_id'	=> $data['service_id'],
            'task_type'     =>$data['task_type'],
            'weibao_type'   => '1'
        );
        $name=$data['photo_names'];
        for($i = 0; $i < count($path_url) - 1; $i++){
            $album['name']=$name[$i];
            $album['url']=$path_url[$i];

            Db::name("serviceConfirm")->insert($album);
        }

        // 维修后添加的数组
        $album1 = array(
            'service_id'	=> $data['service_id'],
            'task_type'     =>$data['task_type'],
            'weibao_type'   => '2'
        );
        $name1=$data['photo_names1'];
        for($i = 0; $i < count($path_url1) - 1; $i++){
            $album1['name']=$name1[$i];
            $album1['url']=$path_url1[$i];

            Db::name("serviceConfirm")->insert($album1);
        }

        // 更新落葬管理表的确认内容字段
        $data11 =  Db::name("serviceWeibao")
            ->where('id', $data['service_id'])
            ->find();
        $data11['confirm_content'] = $data['confirm_content'];
        $data11['service_status'] = '4';
        Db::name("serviceWeibao")->update($data11);

        // 墓碑换新:  服务管理点击完成后做下面处理：如果已经超质保了，按照办理时间延期一年，没超质保就不延期    更新维护期止的那个字段
        $order_info = Db::name("order")->where("tomb_id",$data11['tomb_id'])->where("customer_id",$data11['customer_id'])->find();

        if($order_info['whq_end_date']<time()){
            Db::name("order")->where("tomb_id",$data11['tomb_id'])->where("customer_id",$data11['customer_id'])->update(["whq_end_date"=>strtotime("+1 year")]);
        }

        $this->success("添加成功！", url("Service/weibaoindex"));
    }


    /*维保任务完成*/
    public function weibao_edit(){
        if ($this->request->isPost()){



            $this->success('操作成功');
        }
        $id = $this->request->param('id');
        $results = MaintenanceProjectModel::where(['wb_id'=>$id])->select();

        $this->assign("results", $results);
        return $this->fetch();
    }

    /* 完成*/
    public function move_edit(){
        if ($this->request->isPost()){

            $this->success('操作成功');
        }
        $id = $this->request->param('id');
//        $results = MaintenanceProjectModel::where(['wb_id'=>$id])->select();
        $this->assign("results", []);
        return $this->fetch();
    }



    //任务确认
    public function task_confirmation(){
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $type = $this->request->param('t',0);
            $id = $this->request->param('id',0);
            if ($type=='l'){
                ServiceBuriedModel::update(['service_status'=>2,'receive_user'=>cmf_get_current_admin_id()],['id'=>$id]);
                $danju_url = url('Print/print_cert')."?mark=2&type=l&id={$id}";
                return json(['danju_url'=>$danju_url,'code'=>0,'msg'=>'']);
            }elseif ($type=='j'){
                ServiceDepositModel::update(['service_status'=>2,'receive_user'=>cmf_get_current_admin_id(),'add_time'=>time()],['id'=>$id]);
                $danju_url = url('Print/print_cert')."?mark=2&type=j&id={$id}";
                return json(['danju_url'=>$danju_url,'code'=>0,'msg'=>'']);
            }elseif ($type=='q'){
                ServiceMoveModel::update(['service_status'=>2,'receive_user'=>cmf_get_current_admin_id(),'add_time'=>time()],['id'=>$id]);
                $danju_url = url('Print/print_cert')."?mark=2&type=q&id={$id}";
                return json(['danju_url'=>$danju_url,'code'=>0,'msg'=>'']);
            }elseif ($type=='w'){
                ServiceWeibaoModel::update(['service_status'=>2,'receive_user'=>cmf_get_current_admin_id(),'add_time'=>time()],['id'=>$id]);
                $danju_url = url('Print/print_cert')."?mark=2&type=w&id={$id}";
                return json(['danju_url'=>$danju_url,'code'=>0,'msg'=>'']);
            }

            return json(['code'=>1,'msg'=>'失败']);
        }
    }




    /*附件添加--跳转*/
    public function add()
    {
        return $this->fetch();
    }

    /*附件添加--保存*/
    public function add_post()
    {
        $data = $this->request->param();
        $data['add_time'] = time();
        $data['add_user'] = cmf_get_current_admin_id();
        Db::name("annex")->insert($data);
        $this->success("添加成功！", url("Annex/index"));
    }

    /*附件编辑--跳转传值*/
    public function edit()
    {
        $id = $this->request->param('id');
        $result = Db::name("annex")
            ->where('id', $id)
            ->find();

        $this->assign($result);
        return $this->fetch();
    }

    /*附件编辑--保存*/
    public function edit_post()
    {
        $data = $this->request->param();

        Db::name("annex")->update($data);
        $this->success("保存成功", url("Annex/index"));
    }

    /*附件删除*/
    public function delete()
    {
        $data = $this->request->param();

        Db::name("annex")->delete($data);
        $this->success("删除成功", url("Annex/index"));
    }
}